package com.smartalarmclock.Logic;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneCallBroadcastReceiver extends BroadcastReceiver {
	Context context = null;
 	private static final String TAG = "Phone call";
 	private ITelephony telephonyService;

 	@Override
 	public void onReceive(Context context, Intent intent) {
 		Bundle bundle = intent.getExtras();
 		String phoneNr= bundle.getString("incoming_number");
 		
 		Log.v(TAG, "Receving.... phoneNr: "+phoneNr);
  
 		TelephonyManager telephony = (TelephonyManager) 
 				context.getSystemService(Context.TELEPHONY_SERVICE);  
 		try {
 			Class<?> c = Class.forName(telephony.getClass().getName());
 			Method m = c.getDeclaredMethod("getITelephony");
 			m.setAccessible(true);
 			telephonyService = (ITelephony) m.invoke(telephony);
 			//telephonyService.silenceRinger(); - this is not possible in 2.33 and above. No need for it either.
 			
 			StringBuilder sb = new StringBuilder();
 			
 			if (AcAutoResponseService.AcAutoResponseServiceStatic.ShouldDeclineCall(phoneNr, sb, context))
 			{
 				telephonyService.endCall(); // This is what actually ends the call.
 			}
 			else if (AcAutoResponseService.AcAutoResponseServiceStatic.ShouldSilenceRinger(phoneNr, sb, context))
 			{
 				AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
 	 			audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
 			}
 			
 			sendSMS(phoneNr, sb.toString());
 			
 			
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
  
 	}
 	
 	public void sendSMS(String i_PhoneNumber, String i_Response) {

 	    SmsManager smsManager = SmsManager.getDefault();
 	    smsManager.sendTextMessage(i_PhoneNumber, null, i_Response, null, null);
 	}
}